package com.sun.androidexerciseproject.widget.activity.ui;

import android.app.SearchManager;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;

import android.view.MenuItem;
import com.sun.androidexerciseproject.widget.R;
import com.sun.androidexerciseproject.widget.util.LogUtil;

public class SearchableActivity extends AppCompatActivity {
    public static final String JARGON = "JARGON";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_other);
        initView();
        handleIntent(getIntent());
    }

    private void initView() {
        Toolbar toolbar = (Toolbar) findViewById(R.id.my_toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_setting, menu);
        return super.onCreateOptionsMenu(menu);
    }


    @Override
    protected void onNewIntent(Intent intent) {
        LogUtil.log("onNewIntent");
        setIntent(intent);
        handleIntent(intent);
    }

    private void handleIntent(Intent intent) {
        if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
            String query = intent.getStringExtra(SearchManager.QUERY);
            if (!TextUtils.isEmpty(query)) {
                doSearch(query);
            }
            Bundle bundle = intent.getBundleExtra(SearchManager.APP_DATA);
            if (null != bundle) {
                boolean result = bundle.getBoolean(JARGON, false);
                LogUtil.log("handleIntent result " + result);
            }
        }
    }

    private void doSearch(String query) {
        LogUtil.log("doSearch query " + query);
    }

    @Override
    public boolean onSearchRequested() {
        LogUtil.log("onSearchRequested query ");
        return super.onSearchRequested();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_fav:
                return true;
            case R.id.action_setting:
                return true;
            case R.id.item_search:
                onSearchRequested();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
}
